package chapter05.testservicelistener;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;

public class Activator implements BundleActivator, ServiceListener {

	public void start(BundleContext context) throws Exception {
		context.addServiceListener(this);
	}
	
	public void stop(BundleContext context) throws Exception {
		context.removeServiceListener(this);
	}

	@Override
	public void serviceChanged(ServiceEvent event) {
		ServiceReference sr = event.getServiceReference();
		String serviceClass = ((String[])sr.getProperty("objectClass"))[0];
		String serviceVendor = sr.getProperty(org.osgi.framework.Constants.SERVICE_VENDOR).toString();
		String serviceId = sr.getProperty(org.osgi.framework.Constants.SERVICE_ID).toString();
		
		System.out.println("Service + [" + serviceClass + "|" + serviceVendor + "|" + serviceId + "] " 
							+ getServiceStateName(event.getType()));
		
	}
	
	private String getServiceStateName(int state){
		switch(state){
		case ServiceEvent.REGISTERED:
			return "REGISTERED";
		case ServiceEvent.MODIFIED:
			return "MODIFIED";
		case ServiceEvent.UNREGISTERING:
			return "UNREGISTERING";
		default:
			return Integer.toHexString(state);
		}
				
	}

	
	
}
